package com.hs.shirodemo2.controller;

import com.github.pagehelper.PageInfo;
import com.hs.shirodemo2.constant.CommonConstant;
import com.hs.shirodemo2.entity.Student;
import com.hs.shirodemo2.service.StudentService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    /*
     * 新增
     */
    @RequiresPermissions("user:add")
    @PostMapping("/add")
    public String add(Student student) {
        studentService.add(student);
        return "redirect:/student/find";
    }

    /*
     * 修改
     */
    @RequiresPermissions("user:edit")
    @PostMapping("/edit")
    public String edit(Student student) {
        studentService.edit(student);
        return "redirect:/student/find";
    }

    /*
     * 删除
     */
    @RequiresPermissions("user:remove")
    @GetMapping("/remove/{id}")
    public String remove(@PathVariable Integer id) {
        studentService.remove(id);
        return "redirect:/student/find";
    }

    /*
     * 批量删除
     */
    @GetMapping("/remove")
    public String removeBatch(Integer[] ids) {
        studentService.removeBatch(ids);
        return "redirect:/student/find";
    }

    /*
     * 单条查询
     */
    @GetMapping("/find/{id}")
    public String findById(@PathVariable Integer id, Model model) {
        Student student = studentService.findById(id);
        model.addAttribute("student", student);
        //跳转修改学生的视图
        return "student/edit";
    }

    /*
     * 分页查询
     * @param pageNum 页码
     * @param pageSize 每页条目数
     * @param student 包含查询条件的实体
     * @param model 用来向request域存储数据的ui
     * @return java.lang.String 跳转学生列表页的视图
     *
     * 接收到的请求没有pageNum，默认值1
     * 接收到的请求没有pageSize，默认值5
     */
    @GetMapping("/find")
    public String findPage(@RequestParam(value = CommonConstant.PAGE_NUM, required = false, defaultValue = CommonConstant.PAGE_NUM_DEFAULT) Integer pageNum,
                           @RequestParam(value = CommonConstant.PAGE_SIZE, required = false, defaultValue = CommonConstant.PAGE_SIZE_DEFAULT) Integer pageSize,
                           Student student, Model model) {
        PageInfo pageInfo = studentService.findPage(pageNum, pageSize, student);
        model.addAttribute("pageInfo", pageInfo);
        return "student/list";
    }
}